% Basic Introduction:
% [SM_diag]=SpaFun_LongToDiag(SM_long,[D1;D2])
% This function diagonalizes a long blockwise matrix from dimension
% [#D*D1,D2] to [#D*D1,#D*D2], where #D is the number of the blocks
% in a matrix.
% Example:
% If size(A_i)=[D1,D2] and #D=3, then this function will transform a matrix
% [A_1;A_2;A_3] to diag(A_1,A_2,A_3) in the sparse form.

function SM_diag=SpaFun_Long2Diag(SM_long,DimInfo)

D1              =   DimInfo(1);
D2              =   DimInfo(2);

[Li,Lj,Val]     =   find(SM_long);
multiple        =   size(SM_long,1)/D1;
if isnan(multiple) || isinf(multiple)
    error('Dimension Information is not correct: Inf and NaN pump up!\n');
elseif floor(multiple)~=multiple
    error('Dimension Information is not correct: the multiple is not integer!\n');
else
    Di              =   Li;
    Dj              =   (ceil(Li/D1)-1)*D2+Lj;
    SM_diag         =   sparse(Di,Dj,Val,size(SM_long,1),multiple*D2);
end

